package com.projles.release1;

import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.anddev.andengine.entity.Entity;
import org.anddev.andengine.entity.primitive.Rectangle;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener;
import org.anddev.andengine.entity.scene.background.ColorBackground;
import org.anddev.andengine.entity.sprite.Sprite;
import org.anddev.andengine.entity.util.FPSLogger;
import org.anddev.andengine.input.touch.TouchEvent;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
import org.anddev.andengine.ui.activity.BaseGameActivity;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.widget.Toast;

import com.projles.release1.database.Jogador;
import com.projles.release1.licoes.Instrumento;
import com.projles.release1.licoes.Licao;
import com.projles.release1.licoes.Nota;
import com.projles.util.TocadorSons;
import com.projles.util.Utils;

public class ModoLicaoActivity extends  BaseGameActivity implements IOnSceneTouchListener{

    private static final int CAMERA_WIDTH = 720;
    private static final int CAMERA_HEIGHT = 480;
    
    
    private static final int LAYER_BACKGROUND     = 0;
	private static final int LAYER_AVISO   = 1;
	private static final int LAYER_DESTRAVAR   = 2;
	
	private int numDeAcertos = 0;
	private double porcentagemDeAcertos;
	private int numDeErros = 0;
	
    private Camera mCamera;
    
    private BitmapTextureAtlas mBitmapBackground;
    private TextureRegion mTextureBackground;
    private Sprite mSpriteBackground;
    
    private BitmapTextureAtlas mBitmapLiberaLicao;
    private TextureRegion mTextureLiberaLicao;
    private Sprite mSpriteLiberaLicao;
    
    private BitmapTextureAtlas mBitmapPratoAtaque;
    private TextureRegion mTexturePratoAtaque;
    
    private BitmapTextureAtlas mBitmapErroPratoAtaque;
    private TextureRegion mTextureErroPratoAtaque;
    
    private BitmapTextureAtlas mBitmapTom1;
    private TextureRegion mTextureTom1;
    
    private BitmapTextureAtlas mBitmapErroTom1;
    private TextureRegion mTextureErroTom1;
    
    private BitmapTextureAtlas mBitmapTom2;
    private TextureRegion mTextureTom2;
    
    private BitmapTextureAtlas mBitmapErroTom2;
    private TextureRegion mTextureErroTom2;
    
    private BitmapTextureAtlas mBitmapPratoConducao;
    private TextureRegion mTexturePratoConducao;
    
    private BitmapTextureAtlas mBitmapErroPratoConducao;
    private TextureRegion mTextureErroPratoConducao;
    
    
    private BitmapTextureAtlas mBitmapSurdo;
    private TextureRegion mTextureSurdo;
    
    private BitmapTextureAtlas mBitmapErroSurdo;
    private TextureRegion mTextureErroSurdo;
    
    
    private BitmapTextureAtlas mBitmapBumbo;
    private TextureRegion mTextureBumbo;
    
    private BitmapTextureAtlas mBitmapErroBumbo;
    private TextureRegion mTextureErroBumbo;
    
    
    private BitmapTextureAtlas mBitmapCaixa;
    private TextureRegion mTextureCaixa;
    
    private BitmapTextureAtlas mBitmapErroCaixa;
    private TextureRegion mTextureErroCaixa;
    
    private BitmapTextureAtlas mBitmapChimbal;
    private TextureRegion mTextureChimbal;
    
    private BitmapTextureAtlas mBitmapErroChimbal;
    private TextureRegion mTextureErroChimbal;
    
    private Sprite mSpriteAviso;
    
    private Scene scene;
    
    private Rectangle areaBumbo;
    private Rectangle areaChimbal;
    private Rectangle areaTom1;
    private Rectangle areaTom2;
    private Rectangle areaPratoConducao;
    private Rectangle areaPratoAtaque;
    private Rectangle areaSurdo;
    private Rectangle areaCaixa;
    
    private TocadorSons player;
    
    private CountDownTimer countdown;
    private int tick = 1;
    private long tempoTotalLicao; //em milisegundos
    private Licao licaoAtual;
    private Nota notaAtual;
    private int instrumentoTocado;
    private boolean acertouNota = false;
    private boolean telatravada = true;
    
    private int centerX;
    private int centerY;
   
    
    private TextureRegion[] texturasBrancas = new TextureRegion[8];
    private TextureRegion[] texturasVermelhas = new TextureRegion[8];

    private Jogador jogador;
    
    @Override
    public Engine onLoadEngine() {
    	
    	player = TocadorSons.getPlayer(this);
    	
    	Bundle params = getIntent().getExtras();
        jogador = (Jogador) params.get("jogador");
        String idLicao = params.getString("licao");
    	
    	//TODO - receber a licao da home - criar outras licoes///////////////////////////////////////////////
        
    	licaoAtual = jogador.getLicao(idLicao);
    	notaAtual = licaoAtual.getProximaNota();
    	tempoTotalLicao = (long) ((licaoAtual.getTempoTotal()*0.5)*1000);    // transformando o tempo max em milisegundos
    	
    	mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
    	return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), mCamera));
    }

    @Override
    public void onLoadResources() {
    	BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");

    	
    	mBitmapBackground = new BitmapTextureAtlas(1024, 1024, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
        mTextureBackground = BitmapTextureAtlasTextureRegionFactory.createFromAsset(mBitmapBackground, this, "bateria.png", 0, 0);
    

        carregaImagensBrancas();
    	
    	carregaImagensVermelhas();
    	
    	mBitmapLiberaLicao = new BitmapTextureAtlas(1024, 1024, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
        mTextureLiberaLicao = BitmapTextureAtlasTextureRegionFactory.createFromAsset(mBitmapLiberaLicao, this, "start_time.png", 0, 0);
    
        
        mEngine.getTextureManager().loadTextures(mBitmapLiberaLicao, mBitmapBackground, mBitmapPratoAtaque, mBitmapTom1, 
				 								 mBitmapTom2, mBitmapPratoConducao, mBitmapSurdo, 
				 								 mBitmapBumbo, mBitmapCaixa, mBitmapChimbal,
				 								 mBitmapErroPratoAtaque, mBitmapErroTom1, 
				 								 mBitmapErroTom2, mBitmapErroPratoConducao, mBitmapErroSurdo, 
				 								 mBitmapErroBumbo, mBitmapErroCaixa, mBitmapErroChimbal);
        
    }



	@Override
    public Scene onLoadScene() {
    	
    	mEngine.registerUpdateHandler(new FPSLogger());

        scene = new Scene();
        scene.setOnSceneTouchListener(this);
        scene.setBackground(new ColorBackground(0, 0, 0));
        
        scene.attachChild(new Entity());
        scene.attachChild(new Entity());
        scene.attachChild(new Entity());
        

        /* Calculate the coordinates for the face, so its centered on the camera. */
        centerX = (CAMERA_WIDTH - mTextureBackground.getWidth()) / 2;
        centerY = (CAMERA_HEIGHT - mTextureBackground.getHeight()) / 2;
        
        mSpriteBackground = new Sprite(centerX, centerY, mTextureBackground);
        scene.getChild(LAYER_BACKGROUND).attachChild(mSpriteBackground);

        mSpriteLiberaLicao = new Sprite(centerX, centerY, mTextureLiberaLicao);
        scene.getChild(LAYER_DESTRAVAR).attachChild(mSpriteLiberaLicao);
        
        
        System.out.println(tempoTotalLicao*0.5);
        
        countdown = new CountDownTimer(tempoTotalLicao, 500) {    /// antes era 1000 <-----
			
			@Override
			public void onTick(long tempoRestante) {
				
				System.out.println(tick);
				
				if (tick > notaAtual.getTempo() && tick <= licaoAtual.getTempoMaximoNota()) {   // se estiver dentro do intervalo da nota
					
					if (instrumentoTocado == notaAtual.getInstrumento() && !acertouNota) {  // clicou durante o intervalo de aceitacao
						acertouNota = true;
						numDeAcertos++;
					}
					
					
					scene.getChild(LAYER_AVISO).detachChildren();
					mSpriteAviso = new Sprite(centerX, centerY, texturasBrancas[notaAtual.getInstrumento()]);
					scene.getChild(LAYER_AVISO).attachChild(mSpriteAviso);
					
					if (tick == licaoAtual.getTempoMaximoNota()) {   // soh muda de nota qnd o intervalo de tempo acaba
						
						if (!acertouNota) {
							scene.getChild(LAYER_AVISO).detachChildren();
							mSpriteAviso = new Sprite(centerX, centerY, texturasVermelhas[notaAtual.getInstrumento()]);
							scene.getChild(LAYER_AVISO).attachChild(mSpriteAviso);
						}
						
						acertouNota = false;
						if (!licaoAtual.ehFimLicao()) {
							notaAtual = licaoAtual.getProximaNota();
						}
					}
					
				}
				else {
					instrumentoTocado = -1;
					
					scene.getChild(LAYER_AVISO).detachChildren();
				}
				
				tick++;
			}
			
			@Override
			public void onFinish() {
				
				porcentagemDeAcertos = ((double)numDeAcertos)/licaoAtual.getNumDeNotas();
				numDeErros = licaoAtual.getNumDeNotas() - numDeAcertos;       // Wagner - aqui q tah o erro de nao contabilizar os acertos
				
				Toast.makeText(ModoLicaoActivity.this, 
						       "Acertou: "  + 
				               numDeAcertos + 
				               " nota(s)\nErrou: " + 
				               numDeErros + 
				               " nota(s)\nConseguindo " + 
				               Utils.formataPorcentagem(porcentagemDeAcertos) +  
				               " de acerto.",
				               Toast.LENGTH_LONG).show();

				jogador.setStatus(licaoAtual.getIdentificador(), porcentagemDeAcertos);
				
				if (porcentagemDeAcertos >= licaoAtual.pontuacaoMinima()) {
					
				}
				
				licaoAtual.finalizarLicao(porcentagemDeAcertos);
				finalizarActivity();
			}
		};
        
		carregaAreas();
        
        return scene;
    }
    
	
    private void finalizarActivity() {
    	getIntent().putExtra("jogadorAlterado", jogador);
    	this.setResult(RESULT_OK, getIntent());
    	finish();
    }
    
    @Override
	protected void onStop() {
		super.onStop();
		countdown.cancel();
	}


	
    @Override
    public void onLoadComplete() {
    }

	@Override
	public boolean onSceneTouchEvent(Scene pScene, TouchEvent pSceneTouchEvent) {
		
		if (telatravada && mSpriteLiberaLicao.contains(pSceneTouchEvent.getX(), pSceneTouchEvent.getY())) {   // caso ele clique em qq parte da tela enquanto a tela estah travada
			
			scene.getChild(LAYER_DESTRAVAR).setVisible(false);
			telatravada = false;
			countdown.start();
		}
		
		else {
			
			if (areaBumbo.contains(pSceneTouchEvent.getX(), pSceneTouchEvent.getY())) {
				player.bumbo();
				instrumentoTocado = Instrumento.BUMBO;	        
			}
			else if (areaSurdo.contains(pSceneTouchEvent.getX(), pSceneTouchEvent.getY())) {
				player.surdo();
				instrumentoTocado = Instrumento.SURDO;
			}
			else if (areaCaixa.contains(pSceneTouchEvent.getX(), pSceneTouchEvent.getY())) {
				player.caixa();
				instrumentoTocado = Instrumento.CAIXA;
			}
			else if (areaTom1.contains(pSceneTouchEvent.getX(), pSceneTouchEvent.getY())) {
				player.tom1();
				instrumentoTocado = Instrumento.TOM1;
			}
			else if (areaTom2.contains(pSceneTouchEvent.getX(), pSceneTouchEvent.getY())) {
				player.tom2();
				instrumentoTocado = Instrumento.TOM2;
			}
			else if (areaPratoConducao.contains(pSceneTouchEvent.getX(), pSceneTouchEvent.getY())) {
				player.pratoConducao();
				instrumentoTocado = Instrumento.PRATO_CONDUCAO;
			}
			else if (areaChimbal.contains(pSceneTouchEvent.getX(), pSceneTouchEvent.getY())) {
				player.chimbal();
				instrumentoTocado = Instrumento.CHIMBAL;
			}
			else if (areaPratoAtaque.contains(pSceneTouchEvent.getX(), pSceneTouchEvent.getY())) {
				player.pratoAtaque();
				instrumentoTocado = Instrumento.PRATO_ATAQUE;
			}			
		}
		

		
		return false;
		
	}

	private void carregaImagensBrancas() {
        mBitmapPratoAtaque = new BitmapTextureAtlas(1024, 1024, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
        mTexturePratoAtaque = BitmapTextureAtlasTextureRegionFactory.createFromAsset(mBitmapPratoAtaque, this, "prato_ataque.png", 0, 0);
        texturasBrancas[0] = mTexturePratoAtaque;
        
        mBitmapTom1 = new BitmapTextureAtlas(1024, 1024, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
        mTextureTom1 = BitmapTextureAtlasTextureRegionFactory.createFromAsset(mBitmapTom1, this, "tom1.png", 0, 0);
        texturasBrancas[1] = mTextureTom1;
        
        mBitmapTom2 = new BitmapTextureAtlas(1024, 1024, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
        mTextureTom2 = BitmapTextureAtlasTextureRegionFactory.createFromAsset(mBitmapTom2, this, "tom2.png", 0, 0);
        texturasBrancas[2] = mTextureTom2;

        mBitmapPratoConducao = new BitmapTextureAtlas(1024, 1024, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
        mTexturePratoConducao = BitmapTextureAtlasTextureRegionFactory.createFromAsset(mBitmapPratoConducao, this, "prato_conducao.png", 0, 0);
        texturasBrancas[3] = mTexturePratoConducao;
        
        mBitmapSurdo = new BitmapTextureAtlas(1024, 1024, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
        mTextureSurdo = BitmapTextureAtlasTextureRegionFactory.createFromAsset(mBitmapSurdo, this, "surdo.png", 0, 0);
        texturasBrancas[4] = mTextureSurdo;
        
        mBitmapBumbo = new BitmapTextureAtlas(1024, 1024, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
        mTextureBumbo = BitmapTextureAtlasTextureRegionFactory.createFromAsset(mBitmapBumbo, this, "bumbo.png", 0, 0);
        texturasBrancas[5] = mTextureBumbo;
        
        mBitmapCaixa = new BitmapTextureAtlas(1024, 1024, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
        mTextureCaixa = BitmapTextureAtlasTextureRegionFactory.createFromAsset(mBitmapCaixa, this, "caixa.png", 0, 0);
        texturasBrancas[6] = mTextureCaixa;
        
        mBitmapChimbal = new BitmapTextureAtlas(1024, 1024, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
        mTextureChimbal = BitmapTextureAtlasTextureRegionFactory.createFromAsset(mBitmapChimbal, this, "chimbal.png", 0, 0);
        texturasBrancas[7] = mTextureChimbal;
        
        
	}
	
	private void carregaImagensVermelhas() {
        
        mBitmapErroPratoAtaque = new BitmapTextureAtlas(1024, 1024, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
        mTextureErroPratoAtaque = BitmapTextureAtlasTextureRegionFactory.createFromAsset(mBitmapErroPratoAtaque, this, "prato_ataqueE.png", 0, 0);
        texturasVermelhas[0] = mTextureErroPratoAtaque; 
        
        mBitmapErroTom1 = new BitmapTextureAtlas(1024, 1024, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
        mTextureErroTom1 = BitmapTextureAtlasTextureRegionFactory.createFromAsset(mBitmapErroTom1, this, "tom1E.png", 0, 0);
        texturasVermelhas[1] = mTextureErroTom1;
        
        mBitmapErroTom2 = new BitmapTextureAtlas(1024, 1024, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
        mTextureErroTom2 = BitmapTextureAtlasTextureRegionFactory.createFromAsset(mBitmapErroTom2, this, "tom2E.png", 0, 0);
        texturasVermelhas[2] = mTextureErroTom2;

        mBitmapErroPratoConducao = new BitmapTextureAtlas(1024, 1024, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
        mTextureErroPratoConducao = BitmapTextureAtlasTextureRegionFactory.createFromAsset(mBitmapErroPratoConducao, this, "prato_conducaoE.png", 0, 0);
        texturasVermelhas[3] = mTextureErroPratoConducao;
        
        mBitmapErroSurdo = new BitmapTextureAtlas(1024, 1024, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
        mTextureErroSurdo = BitmapTextureAtlasTextureRegionFactory.createFromAsset(mBitmapErroSurdo, this, "surdoE.png", 0, 0);
        texturasVermelhas[4] = mTextureErroSurdo;
        
        mBitmapErroBumbo = new BitmapTextureAtlas(1024, 1024, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
        mTextureErroBumbo = BitmapTextureAtlasTextureRegionFactory.createFromAsset(mBitmapErroBumbo, this, "bumboE.png", 0, 0);
        texturasVermelhas[5] = mTextureErroBumbo;
        
        mBitmapErroCaixa = new BitmapTextureAtlas(1024, 1024, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
        mTextureErroCaixa = BitmapTextureAtlasTextureRegionFactory.createFromAsset(mBitmapErroCaixa, this, "caixaE.png", 0, 0);
        texturasVermelhas[6] = mTextureErroCaixa;
        
        mBitmapErroChimbal = new BitmapTextureAtlas(1024, 1024, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
        mTextureErroChimbal = BitmapTextureAtlasTextureRegionFactory.createFromAsset(mBitmapErroChimbal, this, "chimbalE.png", 0, 0);
        texturasVermelhas[7] = mTextureErroChimbal;		

	}
	
	private void carregaAreas() {
		
		// PRA VER AS AREAS EH SOH COMENTAR AS LINHAS ONDE TEM .setAlpha(0)   <-------------
		
		Entity rectangleGroup = new Entity(CAMERA_WIDTH / 3, CAMERA_HEIGHT / 3);
		
		// vermelho - 
		areaBumbo = makeColoredRectangle(25, 60, 1, 0, 0);
		areaBumbo.setScaleX((float) 0.3);
		areaBumbo.setScaleY((float) 0.7);
		areaBumbo.setAlpha(0);
		
		
		// verde-escuro - block
		areaSurdo = makeColoredRectangle(190, 90, 0, 1, 0);
		areaSurdo.setScaleX((float) 0.8);
		areaSurdo.setScaleY((float) 0.8);
		areaSurdo.setAlpha(0);
		
		
		// azul - block
		areaCaixa = makeColoredRectangle(-60, 90, 0, 0, 1);
		areaCaixa.setScaleX((float) 0.6);
		areaCaixa.setScaleY((float) 0.6);
		areaCaixa.setAlpha(0);
		
		
		// verdezul - block
		areaTom1 = makeColoredRectangle(-60, -70, 0, 1, 1);
		areaTom1.setScaleX((float) 0.7);
		areaTom1.setScaleY((float) 0.7);
		areaTom1.setAlpha(0);
		
		
		// rosa - block
		areaTom2 = makeColoredRectangle(120, -70, 1, 0, 1);
		areaTom2.setScaleX((float) 0.7);
		areaTom2.setScaleY((float) 0.7);
		areaTom2.setAlpha(0);
		
		
		// roxo - block
		areaPratoConducao = makeColoredRectangle(280, -90, (float) 1.5, 0, (float) 1.5);
		areaPratoConducao.setScaleX((float) 0.8);
		areaPratoConducao.setScaleY((float) 0.8);
		areaPratoConducao.setAlpha(0);
		
		
		// cinza - block
		areaPratoAtaque = makeColoredRectangle(-210, -120, (float) 1.5, (float) 1.5, (float) 1.5);
		areaPratoAtaque.setScaleX((float) 0.8);
		areaPratoAtaque.setScaleY((float) 0.8);
		areaPratoAtaque.setAlpha(0);
		
		
		// verde-claro - block
		areaChimbal = makeColoredRectangle(-215, 50, (float) 1.5, 1, 0);
		areaChimbal.setScaleX((float) 0.6);
		areaChimbal.setScaleY((float) 0.6);
		areaChimbal.setAlpha(0);
		
		
		rectangleGroup.attachChild(areaBumbo);
		rectangleGroup.attachChild(areaSurdo);
		rectangleGroup.attachChild(areaCaixa);
		rectangleGroup.attachChild(areaTom1);
		rectangleGroup.attachChild(areaTom2);
		rectangleGroup.attachChild(areaPratoConducao);
		rectangleGroup.attachChild(areaPratoAtaque);
		rectangleGroup.attachChild(areaChimbal);
		
		scene.attachChild(rectangleGroup);
		
	}
	
	private Rectangle makeColoredRectangle(final float pX, final float pY, final float pRed, final float pGreen, final float pBlue) {
        final Rectangle coloredRect = new Rectangle(pX, pY, 180, 180);
        coloredRect.setColor(pRed, pGreen, pBlue);
        return coloredRect;
	}


}


